package config

import (
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql" // 导入MySQL驱动
	"github.com/spf13/viper"
)

// Config 应用配置结构体
type Config struct {
	Server   ServerConfig   `mapstructure:"server"`
	Database DatabaseConfig `mapstructure:"database"`
	Storage  StorageConfig  `mapstructure:"storage"`
	Redis    RedisConfig    `mapstructure:"redis"`
	Kafka    KafkaConfig    `mapstructure:"kafka"`
	MQTT     MQTTConfig     `mapstructure:"mqtt"`
	Pricing  PricingConfig  `mapstructure:"pricing"`
	Device   DeviceConfig   `mapstructure:"device"`
	Logging  LoggingConfig  `mapstructure:"logging"`
}

// ServerConfig HTTP服务器配置
type ServerConfig struct {
	Port         string `mapstructure:"port"`
	ReadTimeout  string `mapstructure:"read_timeout"`
	WriteTimeout string `mapstructure:"write_timeout"`
	IdleTimeout  string `mapstructure:"idle_timeout"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Driver          string `mapstructure:"driver"`
	Host            string `mapstructure:"host"`
	Port            string `mapstructure:"port"`
	User            string `mapstructure:"user"`
	Password        string `mapstructure:"password"`
	DBName          string `mapstructure:"dbname"`
	SSLMode         string `mapstructure:"sslmode"`
	MaxOpenConns    int    `mapstructure:"max_open_conns"`
	MaxIdleConns    int    `mapstructure:"max_idle_conns"`
	ConnMaxLifetime string `mapstructure:"conn_max_lifetime"`
	DSN             string `mapstructure:"dsn"`
}

// StorageConfig 存储相关配置
type StorageConfig struct {
	Type  string          `mapstructure:"type"` // 可选值："redis", "mysql", "mongo" 等
	Redis *RedisConfig    `mapstructure:"redis,omitempty"`
	MySQL *DatabaseConfig `mapstructure:"mysql,omitempty"`
}

// RedisConfig Redis配置
type RedisConfig struct {
	Addr         string `mapstructure:"addr"`
	Password     string `mapstructure:"password"`
	DB           int    `mapstructure:"db"`
	PoolSize     int    `mapstructure:"pool_size"`
	MinIdleConns int    `mapstructure:"min_idle_conns"`
	IdleTimeout  string `mapstructure:"idle_timeout"`
}

// KafkaConfig Kafka配置
type KafkaConfig struct {
	Brokers  []string            `mapstructure:"brokers"`
	GroupID  string              `mapstructure:"group_id"`
	Topics   KafkaTopicsConfig   `mapstructure:"topics"`
	Producer KafkaProducerConfig `mapstructure:"producer"`
	Consumer KafkaConsumerConfig `mapstructure:"consumer"`
}

// KafkaTopicsConfig Kafka主题配置
type KafkaTopicsConfig struct {
	DeviceData     string `mapstructure:"device_data"`
	DeviceCommands string `mapstructure:"device_commands"`
	Transactions   string `mapstructure:"transactions"`
}

// KafkaProducerConfig Kafka生产者配置
type KafkaProducerConfig struct {
	RequiredAcks int    `mapstructure:"required_acks"`
	Compression  string `mapstructure:"compression"`
}

// KafkaConsumerConfig Kafka消费者配置
type KafkaConsumerConfig struct {
	MinFetchBytes int    `mapstructure:"min_fetch_bytes"`
	MaxWaitTime   string `mapstructure:"max_wait_time"`
}

// MQTTConfig MQTT配置
type MQTTConfig struct {
	Broker       string           `mapstructure:"broker"`
	ClientID     string           `mapstructure:"client_id"`
	Username     string           `mapstructure:"username"`
	Password     string           `mapstructure:"password"`
	KeepAlive    string           `mapstructure:"keep_alive"`
	CleanSession bool             `mapstructure:"clean_session"`
	Topics       MQTTTopicsConfig `mapstructure:"topics"`
}

// MQTTTopicsConfig MQTT主题配置
type MQTTTopicsConfig struct {
	DeviceTelemetry string `mapstructure:"device_telemetry"`
	DeviceCommands  string `mapstructure:"device_commands"`
}

// PricingConfig 电价策略配置
type PricingConfig struct {
	UpdateInterval string          `mapstructure:"update_interval"`
	DefaultRate    float64         `mapstructure:"default_rate"`
	TimeRanges     []TimeRangeRate `mapstructure:"time_ranges"`
}

// TimeRangeRate 分时电价配置
type TimeRangeRate struct {
	Start string  `mapstructure:"start"`
	End   string  `mapstructure:"end"`
	Rate  float64 `mapstructure:"rate"`

	StartHour, StartMin int
	EndHour, EndMin     int
}

// DeviceConfig 设备配置
type DeviceConfig struct {
	MaxConnections    int    `mapstructure:"max_connections"`
	HeartbeatInterval string `mapstructure:"heartbeat_interval"`
	ReconnectInterval string `mapstructure:"reconnect_interval"`
}

// LoggingConfig 日志配置
type LoggingConfig struct {
	Level  string `mapstructure:"level"`
	Format string `mapstructure:"format"`
	Output string `mapstructure:"output"`
}

// Load 从文件加载配置
func Load(configPath string) (*Config, error) {
	var cfg Config

	viper.SetConfigFile(configPath)
	viper.SetConfigType("yaml")

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("读取配置文件失败: %w", err)
	}

	// 解析配置到结构体
	if err := viper.Unmarshal(&cfg); err != nil {
		return nil, fmt.Errorf("解析配置失败: %w", err)
	}

	log.Println("配置文件加载成功")
	return &cfg, nil
}
